package com.module.aichat.ui.chatMain.provider

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.View
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.Target
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyEvents
import com.common.app.helper.RouterHelper
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.isNoEmpty
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.utils.JsonUtils
import com.common.base.utils.ToastUtils
import com.common.base.utils.ViewUtils
import com.common.base.widget.CustomTextView
import com.common.base.widget.SCheckBox
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.aichat.R
import com.module.aichat.data.AiChatApi
import com.module.aichat.data.bean.ChatMessageType
import com.module.aichat.data.bean.MsgDirection
import com.module.aichat.data.protocol.messageContent.TextMessageContent
import com.module.aichat.db.table.DBMessage
import com.module.aichat.repo.ChatMessageRepo
import com.module.aichat.ui.widget.inputview.AiSbListAdapter
import io.noties.markwon.Markwon
import io.noties.markwon.ext.tables.TablePlugin
import io.noties.markwon.image.AsyncDrawable
import io.noties.markwon.image.glide.GlideImagesPlugin
import io.noties.markwon.image.glide.GlideImagesPlugin.GlideStore
import io.noties.markwon.syntax.Prism4jThemeDefault
import io.noties.markwon.syntax.SyntaxHighlightPlugin
import io.noties.prism4j.Prism4j
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/06/25
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class TextMsgProvider(override val itemViewType: Int = ChatMessageType.TEXT.value, listener: AiSbListAdapter.OnAiSbListAdapterListener? = null) :
    BaseMessageItemProvider() {

    private val mAdapter by lazy { AiSbListAdapter() }
    private var listener: AiSbListAdapter.OnAiSbListAdapterListener? = null

    var scope = CoroutineScope(Dispatchers.IO)

    val complexMarkwon by lazy { Markwon.builder(context).usePlugin(TablePlugin.create(context))
//                            .usePlugin(SyntaxHighlightPlugin.create(Prism4j(GrammarLocatorDef()), Prism4jThemeDefault.create(0)))
        .usePlugin(GlideImagesPlugin.create(context))
        .usePlugin(GlideImagesPlugin.create(Glide.with(context)))
        .usePlugin(GlideImagesPlugin.create(object : GlideStore {
            override fun load(drawable: AsyncDrawable): RequestBuilder<Drawable> {
                return Glide.with(context)
                    .load(drawable.destination)
                    .placeholder(R.mipmap.ic_logo_launcher)
                    .error(R.mipmap.ic_logo_launcher)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .format(DecodeFormat.PREFER_RGB_565)//设置为这种格式去掉透明度通道，可以减少内存占有
                    .override(ViewUtils.getScreenWidth(), Target.SIZE_ORIGINAL)
                    .fitCenter() // 保持图片比例，适应容器宽度
            }

            override fun cancel(target: Target<*>) {
                Glide.with(context).clear(target)
            }

        })).build() }

    init {
        this.listener = listener
    }

    override fun getContentLayoutId(): Int {
        return R.layout.aichat_provider_text_item
//        addChildClickViewIds(R.id.scbLike, R.id.scbFall)
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun convertContent(helper: BaseViewHolder, message: DBMessage?) {

        helper.setGone(R.id.titleLine, true)
        helper.setGone(R.id.scbLike, true)
        helper.setGone(R.id.scbFall, true)
        helper.setGone(R.id.sbHrv, true)

        if(message?.extra.isNoEmpty()){
            mAdapter.setListener(listener)
            val mStrList : List<String> = JsonUtils.fromJsonList(message?.extra?:"")
            helper.setGone(R.id.sbHrv, mStrList.isNullOrEmpty())
            mStrList.isNullOrEmpty().no {
                helper.getView<RecyclerView>(R.id.sbHrv).adapter = mAdapter
                mAdapter.setList(mStrList)
            }
        }

        message?.content.let {
            val textMsgContent = it as TextMessageContent
            attachView = if (message?.msgDirection == MsgDirection.SEND) {
                helper.setGone(R.id.bodyTotal, true)
                helper.setGone(R.id.messageSend, false)
                helper.setText(R.id.messageSend, textMsgContent.text)
                helper.getView(R.id.messageSend)
            } else {
                helper.setGone(R.id.bodyTotal, false)
                helper.setGone(R.id.messageSend, true)
//                helper.setText(R.id.messageReceive,  msgContentText?.text)

//                Log.e("AIChat-SSE", "_sseData-convertContent:${textMsgContent.text}")

                (textMsgContent.text)?.let { textIt ->
                    // 分步处理
                    val node = complexMarkwon.parse(textIt)
                    val markdown = complexMarkwon.render(node)
                    complexMarkwon.setParsedMarkdown(helper.getView(R.id.messageReceive), markdown)

                    (textIt.isNullOrEmpty()).no {
                        helper.setGone(R.id.titleLine, false)
                        helper.setGone(R.id.scbLike, false)
                        helper.setGone(R.id.scbFall, false)
                    }
                }

                helper.getView<SCheckBox>(R.id.scbLike).let {scbLikeIt->
                    scbLikeIt.setOnClickListener(onClick = object : View.OnClickListener {
                        override fun onClick(p0: View?) {
                            LiveEventBus.get(KeyEvents.KEY_AICHAT_SEND_LIKE_STATE).post(message)
//                            requestMsgFeedback(message,"like", helper.layoutPosition)
                        }
                    })
                    scbLikeIt.initChecked((message?.likeStatus?:0)>0)
                }


                helper.getView<SCheckBox>(R.id.scbFall).let {scbLikeIt->
                    scbLikeIt.setOnClickListener(onClick = object : View.OnClickListener {
                        override fun onClick(p0: View?) {
                            LiveEventBus.get(KeyEvents.KEY_AICHAT_SEND_FALL_STATE).post(message)
//                            requestMsgFeedback(message,"dislike", helper.layoutPosition)
                        }
                    })
                    scbLikeIt.initChecked((message?.fallStatus?:0)>0)
                }

                helper.getView(R.id.messageReceive)

            }

        }
    }

    private fun requestMsgFeedback(message: DBMessage?, rating:String, position:Int) {
        if ((message?.messageId?:"").isNullOrEmpty()) return

        scope.launch {
            val response = RxHttp.postJson(AiChatApi.MSG_FEED_BACK)
            response.add("message_id",message?.messageId?:"")
            (rating == "like").yes {
                response.add("rating",if ((message?.likeStatus?:0)>0) "" else rating)
            }.otherwise {
                response.add("rating",if ((message?.fallStatus?:0)>0) "" else rating)
            }
            response.toFlow<CommonBean<Any>>()
                .catch { e ->
                }.collect {
                    it.isSuccess().yes {
                        it.Data?.apply {
                            message?.let {messageIt->
                                (rating == "like").yes {
                                    message.likeStatus = if (messageIt.likeStatus >0) 0 else 1
                                }.otherwise {
                                    message.fallStatus = if (messageIt.fallStatus >0) 0 else 1
                                }

                                ChatMessageRepo.instance.add2DB(messageIt)
                                doOnUiThread {
//                                    getAdapter()?.notifyDataSetChanged()
                                    getAdapter()?.notifyItemChanged(position)
                                    LiveEventBus.get(KeyEvents.KEY_AICHAT_RHV_ROLL_BOT).post(this)
                                }
                            }

                        }
                    }
                }
        }
    }
}